package view.components
{
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	
	import global.Resource;

	public class LoadingBar extends Sprite
	{
		private var face:DisplayObject;
		private var bg:DisplayObject;
		private var faceM:Shape;
		private var _percent:Number;
		private var faceKey:String;
		private var bgKey:String;
		private var value:Number;
		private var maximum:Number;
		
		public function LoadingBar(faceKey:String = "face_loadingFace",bgKey:String = "face_loadingBg")
		{
			this.faceKey = faceKey;
			this.bgKey = bgKey;
			initImg();
			initMask();
		}
		
		private function initMask():void
		{
			faceM = new Shape();
			addChild(faceM);
			with(faceM.graphics)
			{
				beginFill(0);
				drawRect(face.x,face.y,face.width,face.height);
				endFill();
			}
			face.mask = faceM;
		}
		
		private function initImg():void
		{
			face = Resource.getImg(faceKey);
			bg = Resource.getImg(bgKey);
			addChild(bg);
			addChild(face);
			
			if (bg is TempBitmap)
			{
				bg.addEventListener(Event.COMPLETE,onBgComplete);
			}
		}
		
		private function onBgComplete(event:Event):void
		{
			/*with(faceM.graphics)
			{
				clear();
				beginFill(0);
				drawRect(face.x,face.y,face.width,face.height);
				endFill();
			}*/
			bg.removeEventListener(Event.COMPLETE,onBgComplete);
			dispatchEvent(event);
			
		}
		
		public function setProgress(value:Number, maximum:Number):void
		{
			this.value = value;
			this.maximum = maximum;
			percent = value / maximum;
		}
		
		override public function toString():String
		{
			return value + " / " + maximum;
		}
		
		public function set percent(v:Number):void
		{
			_percent = v;
			//faceM.width = 200 * _percent;
			
			if (_percent > 1)
			{
				_percent = 1;
			}
			else if (_percent < 0)
			{
				percent = 0;
			}
			else if (isNaN(_percent))
			{
				percent = 0;	
			}
			
			
			with(faceM.graphics)
			{
				clear();
				beginFill(0);
				drawRect(face.x,face.y,face.width * _percent,face.height);
				endFill();
			}
			face.mask = faceM;
		}
		
		public function get percent():Number
		{
			return _percent;
		}
	}
}